package com.hengpeng.itfints.service.invest.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.Projections;
import com.hengpeng.common.persist.query.constants.QueryConstants.QueryType;
import com.hengpeng.common.util.DateTimeUtil;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfinbase.en.InvestStatus;
import com.hengpeng.itfinbase.persist.BorrowInfo;
import com.hengpeng.itfinbase.persist.InvestInfo;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfints.controller.investInfo.vo.InvestInfoVo;
import com.hengpeng.itfints.service.ServiceFactory;
import com.hengpeng.itfints.service.invest.InvestInfoService;

@Lazy
@Service
public class InvestInfoServiceImpl implements InvestInfoService {
    @Autowired
    private ServiceFactory serviceFactory;

    @Override
    public List<InvestInfo> queryInvestList(Long borrowId, Long investUserId, InvestStatus status) {
        DynamicQuery query = new DynamicQuery(InvestInfo.class);
        if (borrowId != null) {
            query.eq("borrowInfoId", borrowId);
        }
        if (investUserId != null) {
            query.eq("investUserId", investUserId);
        }
        if(status != null){
        	query.eq("status", status);
        }else{
            query.inArray("status", new InvestStatus[]{InvestStatus.INVESTING,InvestStatus.SUCESS,InvestStatus.LOANED,InvestStatus.LOANING,InvestStatus.RETURNED});
        }
        query.setQueryType(QueryType.JDBC);
        return serviceFactory.getPersistService().find(InvestInfo.class, query);
    }
    
    @Override
	public List<InvestInfoVo> queryInvestHistory(Long borrowId,
			Long investUserId, InvestStatus status) {
    	List<InvestInfoVo> dataList = new ArrayList<InvestInfoVo>();
		DynamicQuery query = new DynamicQuery(InvestInfo.class,"i");
    	query.createAlias(UserInfo.class, "u");
    	query.eqProperty("i.investUserId", "u.id");
        query.addProjection(Projections.property("u.mobile"));//0
        query.addProjection(Projections.property("u.realName"));//1
        query.addProjection(Projections.property("u.cardNumber"));//2
        query.addProjection(Projections.property("i.investTime"));//3
        query.addProjection(Projections.property("i.investMoney"));//4
        
        if (borrowId != null) {
            query.eq("i.borrowInfoId", borrowId);
        }
        if (investUserId != null) {
            query.eq("i.investUserId", investUserId);
        }
        if(status != null){
        	query.eq("i.status", status);
        }else{
            query.inArray("i.status", new InvestStatus[]{InvestStatus.INVESTING,InvestStatus.SUCESS,InvestStatus.LOANED,InvestStatus.LOANING,InvestStatus.RETURNED});
        }
        query.setQueryType(QueryType.JDBC);
        System.out.println(query.getSqlResult().getSql());
        List<Object> list = serviceFactory.getPersistService().findObject(null, query);
        
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Object[] obj = (Object[]) list.get(i);
                InvestInfoVo vo = new InvestInfoVo();
                vo.setMobile(String.valueOf(obj[0]));
                vo.setRealName(String.valueOf(obj[1]));
                vo.setCardNumber(String.valueOf(obj[2]));
                vo.setInvestTime(DateTimeUtil.formatToDate(String.valueOf(obj[3]), DateTimeUtil.DATE_FORMAT_YMDHM));
                vo.setInvestMoney(Long.parseLong(String.valueOf(obj[4])));
                dataList.add(vo);
            }
        }
		return dataList;
	}

    @Override
    public List<InvestInfo> queryAccountInvestList(Long investUserId, String status, String queryTime) {
        DynamicQuery query = new DynamicQuery(InvestInfo.class);
        if (investUserId != null) {
            query.eq("investUserId", investUserId);
        }
        if ("SUCCESS".equals(status)) {
            query.inArray("status", new InvestStatus[] { InvestStatus.SUCESS, InvestStatus.LOANED,
                    InvestStatus.LOANING, InvestStatus.RETURNED });
        } else if ("DEALING".equals(status)) {
            query.inArray("status", new InvestStatus[] { InvestStatus.INVESTING });
        } else if ("FAIL".equals(status)) {
            query.inArray("status", new InvestStatus[] { InvestStatus.FAILURE, InvestStatus.CANCLING,
                    InvestStatus.CANCLED });
        }
        if ("three_day".equals(queryTime)) {// 查询三天以内的记录
            query.ge("investTime", DateTimeUtil.addDate(new Date(), -3));
        } else if ("one_week".equals(queryTime)) {// 查询一周以内的记录
            query.ge("investTime", DateTimeUtil.addDate(new Date(), -7));
        } else if ("one_month".equals(queryTime)) {// 查询一个月之内的记录
            query.ge("investTime", DateTimeUtil.addDate(new Date(), -30));
        } else if ("three_month".equals(queryTime)) {// 查询三个月之内的记录
            query.ge("investTime", DateTimeUtil.addDate(new Date(), -90));
        } else {// 默认显示一周的记录
            query.ge("investTime", DateTimeUtil.addDate(new Date(), -7));
        }
        query.desc("investTime");
        query.setQueryType(QueryType.JDBC);
        // System.out.println(query.getSqlResult().getSql());
        return serviceFactory.getPersistService().find(InvestInfo.class, query);
    }

    @Override
    public List<InvestInfoVo> queryMyInvestList(Long investUserId, InvestStatus status, String arrivalTime,String startInvestTime, String endInvestTime) {
        
        List<InvestInfoVo> dataList = new ArrayList<InvestInfoVo>();
        DynamicQuery query = new DynamicQuery(InvestInfo.class, "i");
        query.createAlias(BorrowInfo.class, "b");
        query.eqProperty("i.borrowInfoId", "b.id");
        query.addProjection(Projections.property("b.borrowName"));//0
        query.addProjection(Projections.property("b.borrowRate"));//1
        query.addProjection(Projections.property("i.investTime"));//2
        query.addProjection(Projections.property("i.investMoney"));//3
        query.addProjection(Projections.property("i.status"));//4
        if (status != null) {
            query.eq("i.status", status);
        } else {// 默认显示回款中
            query.eq("i.status", InvestStatus.LOANED);
        }
        query.eq("i.investUserId", investUserId);
        if (!StringHelper.isEmpty(startInvestTime)) {
            query.ge("date_format(i.investTime,'%Y-%m-%d')", startInvestTime);
		}
        if (!StringHelper.isEmpty(endInvestTime)) {
            query.le("date_format(i.investTime,'%Y-%m-%d')", endInvestTime);
		}
        query.desc("i.investTime");
        query.setQueryType(QueryType.JDBC);
//        System.out.println(query.getSqlResult().getSql());
        List<Object> l = serviceFactory.getPersistService().findObject(null, query);
        if (l != null && l.size() > 0) {
            for (int i = 0; i < l.size(); i++) {
                Object[] obj = (Object[]) l.get(i);
                InvestInfoVo vo = new InvestInfoVo();
                vo.setBorrowName(String.valueOf(obj[0]));
                vo.setBorrowRate(String.valueOf(obj[1]));
                vo.setInvestTime(DateTimeUtil.formatToDate(String.valueOf(obj[2]), DateTimeUtil.DATE_FORMAT_YMD));
                vo.setInvestMoney(Long.parseLong(String.valueOf(obj[3])));
                vo.setStatus(InvestStatus.valueOf(String.valueOf(obj[4])));
                dataList.add(vo);
            }
        }
        return dataList;
    }

    @Override
    public InvestInfoVo getInvestConstruction(Long investUserId) {
        DynamicQuery query = new DynamicQuery(InvestInfo.class,"t");
        query.addProjection(Projections.sum("case t.status when 'LOANED' then 1 else 0 end", "loaned_num"));
        query.addProjection(Projections.sum("case t.status when 'LOANED' then t.investMoney else 0 end", "loaned_money"));
        query.addProjection(Projections.sum("case t.status when 'INVESTING' then 1 else 0 end", "investing_num"));
        query.addProjection(Projections.sum("case t.status when 'INVESTING' then t.investMoney else 0 end", "investing_money"));
        query.addProjection(Projections.sum("case t.status when 'SUCESS' then 1 else 0 end", "sucess_num"));
        query.addProjection(Projections.sum("case t.status when 'SUCESS' then t.investMoney else 0 end", "sucess_money"));
        query.addProjection(Projections.sum("case t.status when 'RETURNED' then 1 else 0 end", "returned_num"));
        query.addProjection(Projections.sum("case t.status when 'RETURNED' then t.investMoney else 0 end", "returned_money"));
        query.eq("t.investUserId", investUserId);
        query.setQueryType(QueryType.JDBC);
        List<Object> list = serviceFactory.getPersistService().findObject(null, query);
        InvestInfoVo investInfoVo = new InvestInfoVo();
        if (list !=null && list.size()>0) {
            Object[] obj = (Object[])list.get(0);
            investInfoVo.setLoanedNum(obj[0] == null ? 0 : Long.parseLong(String.valueOf(obj[0])));
            investInfoVo.setLoanedMoney(obj[1] == null ? 0 : Long.parseLong(String.valueOf(obj[1])));
            investInfoVo.setInvestingNum(obj[2] == null ? 0 : Long.parseLong(String.valueOf(obj[2])));
            investInfoVo.setInvestingMoney(obj[3] == null ? 0 : Long.parseLong(String.valueOf(obj[3])));
            investInfoVo.setSucessNum(obj[4] == null ? 0 : Long.parseLong(String.valueOf(obj[4])));
            investInfoVo.setSucessMoney(obj[5] == null ? 0 : Long.parseLong(String.valueOf(obj[5])));
            investInfoVo.setReturnedNum(obj[6] == null ? 0 : Long.parseLong(String.valueOf(obj[6])));
            investInfoVo.setReturnedMoney(obj[7] == null ? 0 : Long.parseLong(String.valueOf(obj[7])));
        }
        return investInfoVo;
    }

}
